# -*- coding: utf-8 -*-

import os

import pythoncom
from win32com.client import gencache, constants

from py_win import py_dir_path

if __name__ == '__main__':

    word_path = os.path.join(py_dir_path, 'word.docx')
    save_path = os.path.join(py_dir_path, 'save.docx')

    word = gencache.EnsureDispatch("word.application")
    word.Visible = False
    word.DisplayAlerts = False

    # 创建文档
    document = word.Documents.Add()
    # 打开文档
    # document = word.Documents.Open(word_path)

    try:
        document.Paragraphs.Add()
        paragraph = document.Paragraphs(1)
        paragraph.Range.Text = '段落'

        document.Paragraphs.Add()
        paragraph = document.Paragraphs(2)
        table = document.Tables.Add(paragraph.Range, 3, 2)
        table.Style = '网格型'

        document.Paragraphs.Add()
        paragraph = document.Paragraphs(3)
        # shape = document.Shapes.AddChart2()
        shape = document.Shapes.AddChart2(Style=201, Type=52)
        # 设置图表为嵌入型
        shape.WrapFormat.Type = 7

        chart = shape.Chart
        worksheet = chart.ChartData.Workbook.Worksheets(1)

        chart.ChartTitle.Text = '图表标题'
        worksheet.Close()

        # 另存为docx
        document.SaveAs(save_path, FileFormat=12)
    except Exception as e:
        print(e)
        pass
    finally:
        document.Close()
        word.Quit()
        pass
    pass
